package com.smile.frame.websocket.netty.service.handler;

import cn.hutool.json.JSONUtil;
import com.smile.frame.websocket.netty.service.enums.CmdEnum;
import com.smile.frame.websocket.netty.service.dto.WebsocketMessageDTO;
import com.smile.frame.websocket.netty.service.util.BuilderMessageUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 响应数据 handler
 *
 * @author LGC
 * @ChannelHandler.Sharable 保证处理器，在整个生命周期中就是以单例的形式存在
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class DataCmdHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取请求信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("指令cmd data处理");
        // 判断消息实例
        if (!(msg instanceof TextWebSocketFrame)) {
            super.channelRead(ctx, msg);
            return;
        }
        TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
        // 消息内容解析
        WebsocketMessageDTO websocketMessageDTO = JSONUtil.toBean(textWebSocketFrame.text(), WebsocketMessageDTO.class);

        // 响应数据
        if (websocketMessageDTO.getCmd().equals(CmdEnum.DATA.getCode())) {
            TextWebSocketFrame message = BuilderMessageUtil.buildStringMessage(websocketMessageDTO.getClientInfo(), CmdEnum.DATA, String.valueOf(System.currentTimeMillis()));
            ctx.writeAndFlush(message);
        }
        // 其它指令取消读取
        else {
            super.channelRead(ctx, msg);
        }
    }


}
